package own.stu.jobgib.playown.io;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import lombok.Data;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

/**
 * -Djdk.nio.maxCachedBufferSize  限制缓存的 buffer 大小。
 */
public class ReferenceTest {

    public static void main(String[] args) throws Exception {
//        softReference();
//        weakReference();
//        finaize();

        nettyBufferLeak();
    }

    // -Dio.netty.leakDetectionLevel=paranoid
    private static void nettyBufferLeak() throws InterruptedException {

        ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(1024);
        byteBuf = null;
        System.gc();
        PooledByteBufAllocator.DEFAULT.buffer(1024);

        TimeUnit.MINUTES.sleep(10);
    }

    private static void finaize() throws InterruptedException {
        UserInfo userInfo = new UserInfo();
        System.out.println("xxxxxxxxx");
        userInfo = null;
        TimeUnit.MINUTES.sleep(10);
    }

    private static void weakReference() throws InterruptedException {
        UserInfo userInfo = new UserInfo();
        WeakReference<UserInfo> userReference = new WeakReference<>(userInfo);
//        WeakReference<UserInfo> userReference2 = new WeakReference<>(userInfo);
        userInfo = null;
        TimeUnit.MINUTES.sleep(10);
    }

    private static void softReference() throws InterruptedException {
        UserInfo userInfo = new UserInfo();
        SoftReference<UserInfo> userReference = new SoftReference<>(userInfo);
//        WeakReference<UserInfo> userReference2 = new WeakReference<>(userInfo);
        userInfo = null;
        TimeUnit.MINUTES.sleep(10);
    }

    @Data
    static class UserInfo {
        private int age = 10;
        private byte[] privateInfo = new byte[4 * 1024];

        @Override
        protected void finalize() throws Throwable {
            System.out.println(" ======= finalize ======== ");
        }
    }
}


